package com.kekezu.kppw.utils;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.CookieStore;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.cookie.Cookie;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;

import com.kekezu.kppw.R;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Looper;
import android.util.Base64;
import android.util.Log;

public class HttpUtils {
	private static HttpUtils httpUtil;
	private static DefaultHttpClient client;

	private HttpUtils() {

	}

	/**
	 * 方法的描述：httpUtils初始化函数 方法使用案例： HttpUtils httpUtil =
	 * HttpUtils.getInstance();
	 * 
	 * @param 参数的描述
	 * @return 返回类型的描述
	 * @exception 出错信息的描述
	 */
	public static HttpUtils getInstance() {
		if (httpUtil == null) {
			httpUtil = new HttpUtils();
		}
		return httpUtil;
	}

	/**
	 * 方法的描述：httpGet方法 方法使用案例： HttpUtils httpUtil = HttpUtils.getInstance();
	 * String str = httpUtil.httpGet(url);
	 * 
	 * @param 参数的描述
	 *            String url地址
	 * @return 返回类型的描述 String
	 * @exception 出错信息的描述
	 */
	// public String httpGet(String URL) throws Exception
	// {
	// DefaultHttpClient dclient = client; // 保持同一个对象，以保存登录状态
	// if (dclient == null)
	// {
	// dclient = new DefaultHttpClient();
	// client = dclient;
	// }
	//
	// String resultString = "";
	// HttpGet sourceaddr = new HttpGet(URL);
	// HttpResponse httpResponse = dclient.execute(sourceaddr);
	//
	// if (httpResponse.getStatusLine().getStatusCode() == 200)
	// {
	// HttpEntity entity = httpResponse.getEntity();
	// resultString = EntityUtils.toString(entity, HTTP.UTF_8);
	// }
	// else
	// {
	// throw new Exception("can't connect the network");
	// }
	//
	// return resultString.toString();
	// }

	public String httpGet(String URL, Context context) throws Exception {
		DefaultHttpClient dclient = client; // 保持同一个对象，以保存登录状态
		if (dclient == null) {
			dclient = new DefaultHttpClient();
			client = dclient;
		}

		String resultString = null;
		HttpGet sourceaddr = new HttpGet(URL);

		HttpResponse httpResponse = dclient.execute(sourceaddr);

		// 对比值 ConfigInc.getWebURL(context);
		if (RSAUtils.getDecrypt(context).equals(ConfigInc.getWebURL(context))) {
			if (httpResponse.getStatusLine().getStatusCode() == 200) {
				HttpEntity entity = httpResponse.getEntity();
				resultString = EntityUtils.toString(entity, HTTP.UTF_8);
			} else {
				throw new Exception("can't connect the network");
			}
		} else {
			// Toast.makeText(context, "该域名未经官方授权，应用无法启用！",
			// Toast.LENGTH_LONG).show();
			Looper.prepare();
			new AlertDialog.Builder(context)
					.setMessage("该域名未经官方授权，应用无法启用！\r官网地址：http://www.kppw.cn")
					// 设置显示的内容
					.setNegativeButton("退出",
							new DialogInterface.OnClickListener() {// 添加确定按钮
								@Override
								public void onClick(DialogInterface dialog,
										int which) {// 确定按钮的响应事件
									System.exit(0);
								}
							}).setCancelable(false).show();// 在按键响应事件中显示此对话框
			Looper.loop();
		}

		return resultString.toString();
	}

	/**
	 * 方法的描述：httpGet方法 方法使用案例： HttpUtils httpUtil = HttpUtils.getInstance();
	 * String str = httpUtil.httpGet(url,params);
	 * 
	 * @param 参数的描述
	 *            String url地址 Map<String, String> params 参数
	 * @return 返回类型的描述 String
	 * @exception 出错信息的描述
	 */
	public String httpGet(String URL, Map<String, String> params,
			Context context) throws Exception {
		String content = null;
		StringBuilder buf = new StringBuilder();
		if (params != null && params.size() != 0) {
			for (Map.Entry<String, String> entry : params.entrySet()) {
				buf.append(entry.getKey()).append("=")
						.append(URLEncoder.encode(entry.getValue(), "utf-8"));
				buf.append("&");

			}
			buf.deleteCharAt(buf.length() - 1);
		}
		content = buf.toString();

		client = new DefaultHttpClient();
		HttpGet getMethod = new HttpGet(URL + content);

		Log.e("getMethod", URL + content);

		HttpResponse response = null;
		try {
			response = client.execute(getMethod);
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}

		// 对比值 ConfigInc.getWebURL(context);
		if (RSAUtils.getDecrypt(context).equals(ConfigInc.getWebURL(context))) {
			if (response != null
					&& response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {

				content = EntityUtils.toString(response.getEntity());
			}
		} else {
			// Toast.makeText(context, "该域名未经官方授权，应用无法启用！",
			// Toast.LENGTH_LONG).show();
			Looper.prepare();
			new AlertDialog.Builder(context)
					.setMessage("该域名未经官方授权，应用无法启用！\r官网地址：http://www.kppw.cn")
					// 设置显示的内容
					.setNegativeButton("退出",
							new DialogInterface.OnClickListener() {// 添加确定按钮
								@Override
								public void onClick(DialogInterface dialog,
										int which) {// 确定按钮的响应事件
									System.exit(0);
								}
							}).setCancelable(false).show();// 在按键响应事件中显示此对话框
			Looper.loop();
		}

		return content;
	}

	/**
	 * 方法的描述：httpPost函数 方法使用案例： HttpUtils httpUtil = HttpUtils.getInstance();
	 * List <NameValuePair> params = new ArrayList <NameValuePair>();
	 * params.add(new BasicNameValuePair("username","admin")); params.add(new
	 * BasicNameValuePair("password","123456")); String str =
	 * httpUtil.Post(url,params);
	 * 
	 * @param 参数的描述
	 *            String url地址
	 * @return 返回类型的描述 String
	 * @exception 出错信息的描述
	 */
	public String httpPost(String URL, List<NameValuePair> params)
			throws Exception {
		String resultString;
		try {
			HttpPost httpRequest = new HttpPost(URL);

			httpRequest.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
			HttpResponse httpResponse = client.execute(httpRequest);

			if (httpResponse.getStatusLine().getStatusCode() == 200) {
				resultString = readstream(httpResponse.getEntity().getContent());
			} else {
				throw new Exception("can't connect the network");
			}
			return resultString;
		} catch (Exception e) {
			throw e;
		}
	}

	public String httpPost(String URL, MultipartEntity multipart)
			throws Exception {
		String resultString;
		try {
			HttpPost httpRequest = new HttpPost(URL);

			HttpClient client = new DefaultHttpClient();

			httpRequest.setEntity(multipart);

			HttpResponse httpResponse = client.execute(httpRequest);

			if (httpResponse.getStatusLine().getStatusCode() == 200) {
				resultString = readstream(httpResponse.getEntity().getContent());

				Log.e("httpRequest", resultString);
			} else {
				throw new Exception("can't connect the network");
			}
			return resultString;
		} catch (Exception e) {
			throw e;
		}
	}

	public boolean checkNetwork(Context context) {
		ConnectivityManager connectivity = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		if (connectivity != null) {
			NetworkInfo info = connectivity.getActiveNetworkInfo();
			if (info != null) {
				if (info.getState() == NetworkInfo.State.CONNECTED) {
					return true;
				}
			}
		}
		return false;
	}

	private String readstream(InputStream in) {
		StringBuffer resultString = new StringBuffer();
		try {
			BufferedReader inbuff = new BufferedReader(new InputStreamReader(
					in, "UTF-8"));
			String line = "";
			while ((line = inbuff.readLine()) != null) {
				resultString.append('\n');
				resultString.append(line);
			}
		} catch (Exception e) {
		}
		return resultString.toString();
	}

	/**
	 * 上传
	 * 
	 * @param actionURL
	 *            请求地址
	 * @param fileName
	 *            文件路径
	 * @return 服务器返回的json数据
	 */
	public static String httpUpload(String actionURL, String fileName) {
		String strResult = null;
		String end = "\r\n";
		String twoHyphens = "--";
		String boundary = "*****";

		try {
			URL url = new URL(actionURL);
			HttpURLConnection con = (HttpURLConnection) url.openConnection();
			/* 允许Input、Output，不使用Cache */
			con.setDoInput(true);
			con.setDoOutput(true);
			con.setUseCaches(false);
			/* 设定传送的method=POST */
			con.setRequestMethod("POST");
			/* setRequestProperty */
			con.setRequestProperty("Connection", "Keep-Alive");
			con.setRequestProperty("Charset", "UTF-8");
			con.setRequestProperty("Content-Type",
					"multipart/form-data;boundary=" + boundary);
			/* 设定DataOutputStream */
			DataOutputStream ds = new DataOutputStream(con.getOutputStream());
			ds.writeBytes(twoHyphens + boundary + end);
			ds.writeBytes("Content-Disposition: form-data; "
					+ "name=\"uploadfile\";filename=\"" + fileName + "\"" + end);
			ds.writeBytes(end);

			/* 取得文件的FileInputStream */
			FileInputStream fStream = new FileInputStream(fileName);

			/* 设定每次写入1024bytes */
			int bufferSize = 1024;
			byte[] buffer = new byte[bufferSize];
			int length = -1;
			/* 从文件读取数据到缓冲区 */
			while ((length = fStream.read(buffer)) != -1) {
				/* 将数据写入DataOutputStream中 */
				ds.write(buffer, 0, length);
			}
			ds.writeBytes(end);
			ds.writeBytes(twoHyphens + boundary + twoHyphens + end);

			/* close streams */
			fStream.close();
			ds.flush();
			/* 取得Response内容 */
			InputStream is = con.getInputStream();
			int ch;
			StringBuffer b = new StringBuffer();
			while ((ch = is.read()) != -1) {
				b.append((char) ch);
			}

			/* 将Response显示于Dialog */
			// showDialog(b.toString().trim());
			/* 关闭DataOutputStream */
			ds.close();

			JSONObject jsonObject = new JSONObject(b.toString());
			strResult = jsonObject.toString();

		} catch (Exception e) {
			e.printStackTrace();
		}
		return strResult;
	}

	private DefaultHttpClient httpClient;
	private HttpPost httpPost;
	private HttpEntity httpEntity;
	private HttpResponse httpResponse;
	public static String PHPSESSID = null;

	public String executeRequest(String path, List<NameValuePair> params) {
		String ret = "none";
		try {
			this.httpPost = new HttpPost(path);
			httpEntity = new UrlEncodedFormEntity(params, HTTP.UTF_8);
			httpPost.setEntity(httpEntity);
			// 第一次一般是还未被赋值，若有值则将SessionId发给服务器
			if (null != PHPSESSID) {
				httpPost.setHeader("Cookie", "PHPSESSID=" + PHPSESSID);
			}
			System.out.println("-------" + PHPSESSID);
			httpClient = new DefaultHttpClient();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		try {
			httpResponse = httpClient.execute(httpPost);

			if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				HttpEntity entity = httpResponse.getEntity();
				ret = EntityUtils.toString(entity);
				CookieStore mCookieStore = httpClient.getCookieStore();
				List<Cookie> cookies = mCookieStore.getCookies();
				for (int i = 0; i < cookies.size(); i++) {
					// 这里是读取Cookie['PHPSESSID']的值存在静态变量中，保证每次都是同一个值
					if ("PHPSESSID".equals(cookies.get(i).getName())) {
						PHPSESSID = cookies.get(i).getValue();
						break;
					}

				}
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		return ret;
	}

	/**
	 * 使用HttpURLConnection通过POST方式提交请求，并上传文件。
	 * 
	 * @param actionUrl
	 *            访问的url
	 * @param textParams
	 *            文本类型的POST参数(key:value)
	 * @param filePaths
	 *            文件路径的集合
	 * @return 服务器返回的数据，出现异常时返回 null
	 */
	public static String postWithFiles(String actionUrl,
			Map<String, String> textParams, List<String> filePaths) {
		try {
			final String BOUNDARY = UUID.randomUUID().toString();
			final String PREFIX = "--";
			final String LINE_END = "\r\n";

			final String MULTIPART_FROM_DATA = "multipart/form-data";
			final String CHARSET = "UTF-8";

			URL uri = new URL(actionUrl);
			HttpURLConnection conn = (HttpURLConnection) uri.openConnection();

			// 缓存大小
			conn.setChunkedStreamingMode(1024 * 64);
			// 超时
			conn.setReadTimeout(5 * 1000);
			conn.setDoInput(true);
			conn.setDoOutput(true);
			conn.setUseCaches(false);
			conn.setRequestMethod("POST");

			conn.setRequestProperty("connection", "keep-alive");
			conn.setRequestProperty("Charset", "UTF-8");
			conn.setRequestProperty("Content-Type", MULTIPART_FROM_DATA
					+ ";boundary=" + BOUNDARY);

			// 拼接文本类型的参数
			StringBuilder textSb = new StringBuilder();
			if (textParams != null) {
				for (Map.Entry<String, String> entry : textParams.entrySet()) {
					textSb.append(PREFIX).append(BOUNDARY).append(LINE_END);
					textSb.append("Content-Disposition: form-data; name=\""
							+ entry.getKey() + "\"" + LINE_END);
					textSb.append("Content-Type: text/plain; charset="
							+ CHARSET + LINE_END);
					textSb.append("Content-Transfer-Encoding: 8bit" + LINE_END);
					textSb.append(LINE_END);
					textSb.append(entry.getValue());
					textSb.append(LINE_END);
				}
			}

			DataOutputStream outStream = new DataOutputStream(
					conn.getOutputStream());
			outStream.write(textSb.toString().getBytes());

			// 参数POST方式

			// 发送文件数据
			if (filePaths != null) {
				for (String file : filePaths) {
					StringBuilder fileSb = new StringBuilder();
					fileSb.append(PREFIX).append(BOUNDARY).append(LINE_END);
					fileSb.append("Content-Disposition: form-data; name=\"file\"; filename=\""
							+ file.substring(file.lastIndexOf("/") + 1)
							+ "\""
							+ LINE_END);
					fileSb.append("Content-Type: application/octet-stream; charset="
							+ CHARSET + LINE_END);
					fileSb.append(LINE_END);
					outStream.write(fileSb.toString().getBytes());

					InputStream is = new FileInputStream(file);
					byte[] buffer = new byte[1024 * 8];
					int len;
					while ((len = is.read(buffer)) != -1) {
						outStream.write(buffer, 0, len);
					}

					is.close();
					outStream.write(LINE_END.getBytes());
				}
			}

			// 请求结束标志
			outStream.write((PREFIX + BOUNDARY + PREFIX + LINE_END).getBytes());
			outStream.flush();

			// 得到响应码
			int responseCode = conn.getResponseCode();
			BufferedReader br = new BufferedReader(new InputStreamReader(
					conn.getInputStream(), CHARSET));

			StringBuilder resultSb = null;
			String line;
			if (responseCode == 200) {
				resultSb = new StringBuilder();
				while ((line = br.readLine()) != null) {
					resultSb.append(line).append("\n");
				}
			}

			br.close();
			outStream.close();
			conn.disconnect();

			return resultSb == null ? null : resultSb.toString();
		} catch (IOException e) {
			e.printStackTrace();
		}

		return null;
	}
}
